import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_picker/picker.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/pages/home/location/model/today_mileage_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/num_utils.dart';
import 'package:tracker/utils/toast_utils.dart';

/// 里程统计页面
class MileageStatisticsPage extends ConsumerStatefulWidget {
  const MileageStatisticsPage({super.key});

  @override
  ConsumerState<MileageStatisticsPage> createState() => _MileageStatisticsPageState();
}

class _MileageStatisticsPageState extends ConsumerState<MileageStatisticsPage> {
  // 开始时间，默认今天0点.结束时间，默认今天23:59:59
  DateTime startTime = DateTime.now().copyWith(hour: 0, minute: 0, second: 0, millisecond: 0);
  DateTime endTime = DateTime.now().copyWith(hour: 23, minute: 59, second: 59, millisecond: 999);
  double mileage = 0.0;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _fetchMileage();
    });
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: GestureDetector(
          onTap: () {
            Navigator.pop(context);
          },
          child: Container(
            height: kToolbarHeight,
            padding: const EdgeInsets.only(top: 8),
            alignment: Alignment.center,
            child: const Text(' <返回',
                textAlign: TextAlign.center,
                maxLines: 1,
                style: TextStyle(color: Colors.black)),
          ),

        ),
        title: const Text(
          '里程统计',
          style: TextStyle(color: Color(0xFF009FE8), fontSize: 18),
        ),
        centerTitle: true,
        backgroundColor: AppTheme.themeConfig.navBarColor,
        foregroundColor: Colors.white,
      ),
      body: _buildInfoView(),
    );
  }

  void _fetchMileage() async {
    var deviceInfo = ref.watch(deviceInfoProvider);
    var data = {
      'imei': deviceInfo.imei,
      'beginTime': DateUtil.formatDate(startTime, format: 'yyyy-MM-dd HH:mm:ss'),
      'endTime': DateUtil.formatDate(endTime, format: 'yyyy-MM-dd HH:mm:ss'),
    };
    ToastUtils.showLoading();
    final res = await post<TodayMileageResp, TodayMileageResp>('/device/deviceMileage',
        data: data, decodeType: TodayMileageResp());
    res.when(success: (resp) {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {
        var mm = resp.data ?? 0;
        var km = mm / 1000;
        setState(() {
          mileage = km;
        });
      }
    }, failure: (String msg, int code) {
      XLogger.error('获取设备里程：msg: $msg, code: $code');
    });
  }

  /// 里程统计信息
  Widget _buildInfoView() {
    var mileageStr = NumUtils.formatNum(mileage);
    return Column(
      children: [
        Container(
          width: double.infinity,
          height: 160,
          margin: const EdgeInsets.only(right: 10,left: 10,top: 10),
          decoration: BoxDecoration(
            color: Color(0xFFEEEEEF),
            borderRadius: BorderRadius.circular(12),
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(mileageStr, style: TextStyle(color: Colors.black, fontSize: 40)),
              const Text('总里程(km)', style: TextStyle(color: Colors.black, fontSize: 17)),
              // const Text('里程查询结果', style: TextStyle(color: Colors.black, fontSize: 15)),
              // Text.rich(
              //   TextSpan(
              //     children: [
              //       TextSpan(
              //           text: mileageStr,
              //           style: const TextStyle(color: Colors.black, fontSize: 40, fontWeight: FontWeight.bold)),
              //       const TextSpan(text: 'km', style: TextStyle(color: Colors.black, fontSize: 15)),
              //     ],
              //   ),
              // ),


              // const Text('今日里程每小时自动结算一次', style: TextStyle(color: Colors.black, fontSize: 17)),
            ],
          ),
        ),
        Container(
          margin: const EdgeInsets.only(right: 10,left: 10,top: 10),

          child: Column(
            children: [
              // 开始时间， 今日
              Container(
                decoration: BoxDecoration(
                  color: Color(0xFFEEEEEF),
                  borderRadius: BorderRadius.circular(12),
                ),
                height: 50,
                padding: EdgeInsets.only(left: 10, right: 10),
                child: Row(
                  children: [
                    const Text('开始时间', style: TextStyle(fontSize: 17)),
                    Expanded(
                      child: GestureDetector(
                        onTap: () {
                          _showStartTimePicker();
                        },
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Text('${DateUtil.formatDate(startTime, format: 'yyyy-MM-dd')}',
                                style: TextStyle(fontSize: 17)),
                            Icon(Icons.arrow_forward_ios, size: 17, color: Colors.grey),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 10),
              // 结束时间， 今日
              Container(
                decoration: BoxDecoration(
                  color: Color(0xFFEEEEEF),
                  borderRadius: BorderRadius.circular(12),
                ),
                height: 50,
                padding: EdgeInsets.only(left: 10, right: 10),
                child: Row(
                  children: [
                    Container(
                      child: const Text('结束时间', style: TextStyle(fontSize: 17)),
                    ),
                    Expanded(
                      child: GestureDetector(
                        onTap: () {
                          _showEndTimePicker();
                        },
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Text('${DateUtil.formatDate(endTime, format: 'yyyy-MM-dd')}', style: TextStyle(fontSize: 17)),
                            Icon(Icons.arrow_forward_ios, size: 17, color: Colors.grey),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        Spacer(),
        // 查询按钮
        Container(
          margin: const EdgeInsets.only(right: 20,left: 20,top: 10,bottom: 30),
          width: double.infinity,
          height: 40,
          padding: const EdgeInsets.symmetric(horizontal: 50),

          child: ElevatedButton(
            onPressed: () {
              // 开始时间不能大于结束时间
              if (startTime.isAfter(endTime)) {
                ToastUtils.showToast('开始时间不能大于结束时间');
                return;
              }
              // 开始时间和结束时间不能超过7天
              if (endTime.difference(startTime).inDays > 7) {
                ToastUtils.showToast('查询日期范围不能超过7天');
                return;
              }
              _fetchMileage();
            },
            style: ButtonStyle(
              backgroundColor: MaterialStateProperty.all(AppTheme.themeConfig.primaryColor),
              shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(20))),
            ),
            child: const Text('查询', style: TextStyle(fontSize: 18, color: Colors.white)),
          ),
        ),
      ],
    );
  }

  _showStartTimePicker() {
    Picker picker = Picker(
        adapter: DateTimePickerAdapter(
          type: PickerDateTimeType.kYMD,
          isNumberMonth: true,
          yearSuffix: '年',
          monthSuffix: '月',
          daySuffix: '日',
          value: startTime,
          maxValue: DateTime.now().copyWith(hour: 23, minute: 59, second: 59, millisecond: 999),
          minValue: DateTime(2010),
        ),
        title: const Text('选择开始时间'),
        cancelText: '取消',
        confirmText: '确定',
        onConfirm: (Picker picker, List value) {
          setState(() {
            startTime = (picker.adapter as DateTimePickerAdapter).value!;
          });
        });
    picker.showModal(context);
  }

  _showEndTimePicker() {
    Picker picker = Picker(
        adapter: DateTimePickerAdapter(
          type: PickerDateTimeType.kYMD,
          isNumberMonth: true,
          yearSuffix: '年',
          monthSuffix: '月',
          daySuffix: '日',
          value: endTime,
          maxValue: DateTime.now().copyWith(hour: 23, minute: 59, second: 59, millisecond: 999),
          minValue: DateTime(2010),
        ),
        title: const Text('选择开始时间'),
        cancelText: '取消',
        confirmText: '确定',
        onConfirm: (Picker picker, List value) {
          setState(() {
            endTime = (picker.adapter as DateTimePickerAdapter).value!;
          });
        });
    picker.showModal(context);
  }
}
